import { useRequest } from "@umijs/hooks";
import { Button, Form, Input, Layout, Menu, message, Table, Tag } from "antd";
import { Store } from "rc-field-form/lib/interface";
import React, { useState } from "react";
import { getSecretString } from "../../../utils/encrypt";
import { fetchRequest } from "../../../utils/Request";
import { url } from "../../../utils/url";
import XLSX from "xlsx";

interface ValidateState {
  state: "" | "success" | "warning" | "error" | "validating" | undefined;
  help: string | undefined;
}

export default function AddChannelStaff(props: any) {
  const { Content } = Layout;
  const [currentKey, setCurrentKey] = useState("1");
  const [excelTableData, setExcelTableData] = useState<any[]>([]);
  const [batchAddList, setBatchAddList] = useState<any[]>([]);
  const [excelFlag, setExcelFlag] = useState<boolean>(false);
  const [errorData, setErrorData] = useState<any[]>([]);

  const errorcolumns = [
    { title: "错误说明", dataIndex: "errorTitle", key: "errorTitle" },
  ];
  const columns = [
    {
      title: "姓名",
      dataIndex: "name",
      key: "studentName",
      render: (text: string) =>
        text === "" ? <Tag color={"#f50206"}>姓名未填</Tag> : text,
    },
    {
      title: "联系电话",
      dataIndex: "phone",
      key: "phone",
      render: (text: string) => {
        if (text === "") {
          return <Tag color={"#f50206"}>联系电话未填</Tag>;
        }
        if (!/^1[3456789]\d{9}$/.test(text)) {
          return <Tag color={"#f50206"}>{text}:格式异常</Tag>;
        }
        return text;
      },
    },
    {
      title: "渠道名称",
      dataIndex: "channelName",
      key: "channelName",
      render: (text: string) => {
        if (text === "") {
          return <Tag color={"#f50206"}>渠道未填</Tag>;
        }
        return text;
      },
    },
  ];

  // console.log("错误提示")
  // console.log(errorData.data)
  function handleExcelFile(e: any) {
    if (e.target.files[0] === null || e.target.files[0] === undefined) {
      return false;
    }
    let f = e.target.files[0];
    let reader = new FileReader(); // 使用 FileReader 读取数据
    reader.onload = function (e) {
      // 数据读取完成后的回调函数
      try {
        // @ts-ignore
        let workbook = XLSX.read(e.target.result, { type: "binary" });
        let firstSheetName = workbook.SheetNames[0]; // 获取第一个 sheet 的名字
        let worksheet = workbook.Sheets[firstSheetName]; // 获取第一个 sheet 的内容
        let res = XLSX.utils.sheet_to_json(worksheet); // 使用 utils 里的方法转换内容为便于使用的数组
        console.log("res", res);
        const list: any[] = [];
        const addList: any[] = [];
        res.forEach((item: any) => {
          list.push({
            rowNum: item.__rowNum__,
            name:
              item.姓名 === "" || item.姓名 === undefined
                ? ""
                : item.姓名.trim(),
            phone:
              item.联系电话 === "" || item.联系电话 === undefined
                ? ""
                : item.联系电话.trim(),
            channelName:
              item.渠道名称 === "" || item.渠道名称 === undefined
                ? ""
                : item.渠道名称.trim(),
          });

          addList.push({
            name:
              item.姓名 === "" || item.姓名 === undefined
                ? ""
                : item.姓名.trim(),
            phone:
              item.联系电话 === "" || item.联系电话 === undefined
                ? ""
                : item.联系电话.trim(),
            channelName:
              item.渠道名称 === "" || item.渠道名称 === undefined
                ? ""
                : item.渠道名称.trim(),
          });
        });
        // console.log("list数据",list);
        setExcelTableData(list);
        excelDataCheck(addList);
      } catch (e) {
        console.log(e);
        message.error("数据异常！");
      }
    };
    reader.readAsBinaryString(f); // 读取数据
  }

  function excelDataCheck(data: any) {
    let falseFlag = true;
    let repeaterror = "";
    for (let i = 0; i < data.length; i++) {
      if (
        data[i].name === "" ||
        data[i].phone === "" ||
        data[i].channelName === ""
      ) {
        falseFlag = false;
      } else if (!/^1[3456789]\d{9}$/.test(data[i].phone)) {
        falseFlag = false;
      }
      let temp = data[i];
      for (let j = i + 1; j < data.length; j++) {
        if (temp.phone === data[j].phone) {
          repeaterror = "电话号码" + temp.phone + "有多条数据";
          falseFlag = false;
        }
      }
      data[i].phone = getSecretString(data[i].phone);
    }

    if (falseFlag) {
      setBatchAddList(data);
      setExcelFlag(true);
    } else {
      message.error(repeaterror);
      setExcelFlag(false);
    }
  }

  //递归修改item的key
  function disableSelect(arr: any[]) {
    arr.map((item) => {
      delete item.disabled;
      item.key = item.deptID;
      item.value = item.deptID;
      if (
        typeof item.children === "undefined" ||
        item.children === null ||
        item.children.length === 0
      ) {
        return;
      } else {
        item.selectable = false;
        disableSelect(item.children);
      }
    });
  }

  const [form] = Form.useForm();

  const layout = {
    labelCol: { span: 5 },
    wrapperCol: { span: 14 },
  };
  const tailLayout = {
    wrapperCol: { offset: 5, span: 14 },
  };

  function onFinish(value: Store) {
    const data = {
      name: value.name,
      phone: getSecretString(value.phone),
      channelName: value.channelName,
    };
    const params = {
      list: [data],
    };

    // console.log(params)

    addNewStaffOne.run(params);
  }

  function menuClick(e: any) {
    setCurrentKey(e.key);
  }

  function batchAddClick() {
    if (!excelFlag) {
      message.error("excel数据异常，请修改！");
      return;
    }
    const param = {
      list: batchAddList,
    };
    // console.log(param)
    addNewStaff.run(param);
  }

  async function addNewStaffOneRequest(params: any) {
    console.log("单个新增");
    console.log(params);
    try {
      const json = await fetchRequest(url.ADD_CHANNEL_STAFF, params);
      if (json.success) {
        message.destroy();
        message.success("新增成功!");
        props.addSuccess();
      } else {
        message.destroy();
        message.error("新增失败！" + json.info.errorList[0].errorTitle);
      }
    } catch (error: any) {
      message.destroy();
      message.error(error.message);
    }
  }

  async function addNewStaffRequest(params: any) {
    console.log("批量新增");
    console.log(params);
    try {
      const json = await fetchRequest(url.ADD_CHANNEL_STAFF, params);
      if (json.success && json.info.falseCount === 0) {
        message.destroy();
        message.success("新增成功!");
        props.addSuccess();
      } else {
        if (json.info.falseCount != 0) {
          message.destroy();
          message.error(
            "部分导入成功，导入成功" +
              json.info.successCount +
              "条，失败" +
              json.info.falseCount +
              "条！详情请看错误提示！！！"
          );
          setErrorData(json.info.errorList);
        } else {
          message.destroy();
          message.error(json.info.error + "，详情请看错误提示！！！");
        }
      }
    } catch (error: any) {
      message.destroy();
      message.error(error.message);
    }
  }

  const addNewStaff = useRequest(addNewStaffRequest, {
    manual: true,
    loadingDelay: 200,
  });

  const addNewStaffOne = useRequest(addNewStaffOneRequest, {
    manual: true,
    loadingDelay: 200,
  });

  return (
    <div>
      <Menu
        theme={"light"}
        onClick={menuClick}
        mode="horizontal"
        defaultSelectedKeys={["1"]}
      >
        <Menu.Item key="1">单个新增</Menu.Item>
        <Menu.Item key="2">批量新增</Menu.Item>
      </Menu>
      <Content
        className="site-layout"
        style={{ padding: "0 50px", marginTop: 64 }}
      >
        <div
          hidden={currentKey === "2"}
          className="site-layout-background"
          style={{ minHeight: 380 }}
        >
          <Form form={form} {...layout} onFinish={onFinish}>
            <Form.Item
              label="姓名"
              name="name"
              rules={[{ required: true, message: "必须要输入姓名" }]}
            >
              <Input />
            </Form.Item>

            <Form.Item
              label="电话号码"
              name="phone"
              rules={[{ required: true, message: "必须要输入电话号码" }]}
            >
              <Input />
            </Form.Item>

            <Form.Item
              label="渠道名称"
              name="channelName"
              rules={[{ required: true, message: "必须要输入渠道名" }]}
            >
              <Input />
            </Form.Item>

            <Form.Item {...tailLayout}>
              <Button type="primary" htmlType="submit">
                提交
              </Button>
            </Form.Item>
          </Form>
        </div>
        <div
          hidden={currentKey === "1"}
          className="site-layout-background"
          style={{ minHeight: 380 }}
        >
          <div
            style={{
              display: "flex",
              flexDirection: "row",
              alignItems: "center",
              padding: 20,
            }}
          >
            <span>导入模板：</span>
            <a
              href={require("../../../excel/渠道人员批量导入模板.xlsx")}
              download
            >
              渠道人员批量导入模板
            </a>
          </div>
          <div
            style={{
              display: "flex",
              flexDirection: "row",
              alignItems: "center",
              padding: 20,
            }}
          >
            <span>上传文件：</span>
            <input type="file" accept=".xlsx,.xls" onChange={handleExcelFile} />
          </div>
          <div style={{ padding: 20 }}>
            <span>数据预览：</span>
            <Table
              style={{ marginTop: 20 }}
              pagination={{
                hideOnSinglePage: true,
                simple: true,
                pageSize: 10,
                total: excelTableData.length,
              }}
              rowKey={(record: any) => record.rowNum}
              columns={columns}
              dataSource={excelTableData}
            />
          </div>
          <div style={{ padding: 20 }}>
            <Button
              type="primary"
              htmlType="submit"
              onClick={batchAddClick}
              loading={addNewStaff.loading}
            >
              提交
            </Button>
          </div>
          <div style={{ padding: 20 }}>
            <span>错误提示：</span>
            <Table
              style={{ marginTop: 20 }}
              pagination={{
                hideOnSinglePage: true,
                simple: true,
                pageSize: 10,
                total: errorData.length,
              }}
              rowKey={(record: any) => record.rowNum}
              columns={errorcolumns}
              dataSource={errorData}
            />
          </div>
        </div>
      </Content>
    </div>
  );
}
